import abc
from app.libs.exception import APIException, AuthFailed, Forbidden, NotFound


class BaseService:
    __metaclass__ = abc.ABCMeta

    @classmethod
    def optional_404(cls, query_result, error_msg=None, check_list=False):
        """ 如果result为空将会抛出自定义的404异常|列表资源不会抛出异常 """
        return cls.optional(query_result, NotFound(error_msg), check_list)

    @classmethod
    def optional_403(cls, query_result, error_msg=None, check_list=False):
        """ 如果result为空将会抛出自定义的404异常|列表资源不会抛出异常 """
        return cls.optional(query_result, Forbidden(error_msg), check_list)

    @classmethod
    def optional_401(cls, query_result, error_msg=None, check_list=False):
        """ 如果result为空将会抛出自定义的404异常|列表资源不会抛出异常 """
        return cls.optional(query_result, AuthFailed(error_msg), check_list)

    @staticmethod
    def optional(query_result, exception: APIException, check_list=False):
        if query_result is None:
            raise exception
        if check_list and isinstance(query_result, list) and len(query_result) == 0:
            raise exception
        return query_result

        